package com.css.fxfzysx.modules.vaolEngineering.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.modules.lifeline.annotation.ValidationProcessor;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.*;
import com.css.fxfzysx.modules.lifeline.repository.LifelineEngineeringRepository;
import com.css.fxfzysx.modules.lifeline.vo.LifelineIdVo;
import com.css.fxfzysx.modules.lifeline.vo.SmxVersionVo;
import com.css.fxfzysx.modules.vaolEngineering.dto.DataValidation1Dto;
import com.css.fxfzysx.modules.vaolEngineering.dto.DataValidation2Dto;
import com.css.fxfzysx.modules.vaolEngineering.dto.DataValidation3Dto;
import com.css.fxfzysx.modules.vaolEngineering.entity.CpVulnerabilityEntity;
import com.css.fxfzysx.modules.vaolEngineering.entity.newEntity.CztSmxDevicesValueEntity;
import com.css.fxfzysx.modules.vaolEngineering.param.DeleteParam;
import com.css.fxfzysx.modules.vaolEngineering.param.MainTableParam;
import com.css.fxfzysx.modules.vaolEngineering.param.PageParam;
import com.css.fxfzysx.modules.vaolEngineering.param.UpdateParam;
import com.css.fxfzysx.modules.vaolEngineering.param.update.*;
import com.css.fxfzysx.modules.vaolEngineering.repository.*;
import com.css.fxfzysx.modules.vaolEngineering.service.*;
import com.css.fxfzysx.modules.vaolEngineering.vo.LifelineCalculationVo;
import com.css.fxfzysx.modules.vaolEngineering.vo.lifelineCalculation.*;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.css.fxfzysx.util.PlatformPageUtils;
import com.css.fxfzysx.util.PlatformSessionUtils;
import com.css.fxfzysx.web.PlatformSessionContext;
import com.css.fxfzysx.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ValEngineeringServiceImpl implements ValEngineeringService {

    @Autowired
    private ValEngineeringRepository valEngineeringRepository;

    //道路
    @Autowired
    private CarVulnerabilityService carVulnerabilityService;

    //桥梁
    @Autowired
    private CbVulnerabilityService cbVulnerabilityService;

    //通信设备
    @Autowired
    private CeVulnerabilityService ceVulnerabilityService;

    //供电设备
    @Autowired
    private PseVulnerabilityService pseVulnerabilityService;

    @Autowired
    private LifelineEngineeringRepository lifelineEngineeringRepository;

    //供气设施
    @Autowired
    private SgManagementService sgManagementService;

    //变电站
    @Autowired
    private TsVulnerabilityService tsVulnerabilityService;

    //供水设施
    @Autowired
    private WsfManagementService wsfManagementService;

    @Autowired
    private SysRoleService roleService;

    //地下管网
    @Autowired
    private UpNetworkService upNetworkService;

    @Override
    public HashMap<String, Object> page(PageParam param, HttpServletRequest request) {
        int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
        int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
        String role = roleService.getRoleByUserId(PlatformSessionUtils.getUserId());
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        ArrayList<String> roleList = new ArrayList<>();
        for (Map roleMap : roleMaps) {
            String roleCode = (String) roleMap.get("roleCode");
            roleList.add(roleCode);
        }
        return valEngineeringRepository.page(param, page, size, roleList);
    }

    @Override
    public HashMap<String, Object> getVersionByType(Integer type, HttpServletRequest request) {
        int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
        int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
        String userID = PlatformSessionContext.getUserID();
        HashMap<String, Object> data = valEngineeringRepository.getVersionByType(type, page, size, userID);
        data.forEach((k, v) -> {
            if (k.equals("rows")) {
                if (PlatformObjectUtils.isNotEmpty(v)) {
                    ArrayList<SmxVersionVo> voList = new ArrayList<>();
                    List<SmxVersionEntity> list = (List<SmxVersionEntity>) v;
                    list.forEach(it -> {
                        SmxVersionVo vo = new SmxVersionVo();
                        if (PlatformObjectUtils.isNotEmpty(it.getUpdateTime())) {
                            it.setCreateTime(it.getUpdateTime());
                        }
                        BeanUtils.copyProperties(it, vo);
                        vo.setRegion(it.getProvince() + "-" + it.getCity() + "-" + it.getCounty());
                        voList.add(vo);
                    });
                    data.put("rows", voList);
                }
            }
        });
        return data;
    }

    @Override
    public LifelineCalculationVo getByIdAndType(Integer type, String id,Integer bridgeType) {
        LifelineCalculationVo resultVo = new LifelineCalculationVo();
        SmxMainTableEntity tableEntity = valEngineeringRepository.getById(id);
        resultVo.setTableEntity(tableEntity);
        if (type == 1) {
            SmxUpNetworkEntity entity = upNetworkService.getByTableId(id);
            SmxUpNetworkVo upVo = new SmxUpNetworkVo();
            BeanUtils.copyProperties(entity, upVo);
            resultVo.setUpNetworkVo(upVo);
        } else if (type == 2) {
            SmxWaterSupplyEntity entity = wsfManagementService.getByTableId(id);
            SmxWaterSupplyVo vo = new SmxWaterSupplyVo();
            BeanUtils.copyProperties(entity, vo);
            resultVo.setWaterSupplyVo(vo);
        } else if (type == 3) {
            SmxAirReceiverEntity entity = sgManagementService.getByTableId(id);
            SmxAirReceiverVo vo = new SmxAirReceiverVo();
            BeanUtils.copyProperties(entity, vo);
            resultVo.setAirReceiverVo(vo);
        } else if (type == 4) {
            SmxBridgeEntity entity = cbVulnerabilityService.getByTableId(id,bridgeType);
            SmxBridgeVo vo = new SmxBridgeVo();
            BeanUtils.copyProperties(entity, vo);
            resultVo.setBridgeVo(vo);
        } else if (type == 5) {
            SmxRoadEntity entity = carVulnerabilityService.getByTableId(id);
            SmxRoadVo vo = new SmxRoadVo();
            BeanUtils.copyProperties(entity, vo);
            resultVo.setRoadVo(vo);
        } else if (type == 6) {
            List<SmxTransformerSubstationEntity> list = tsVulnerabilityService.getByTableId(id);
            ArrayList<SmxTransformerSubstationVo> voList = new ArrayList<>();
            List<SmxTransformerSubstationValueVo> valueList = tsVulnerabilityService.getValueByTsId(id);
            list.forEach(it -> {
                SmxTransformerSubstationVo vo = new SmxTransformerSubstationVo();
                BeanUtils.copyProperties(it, vo);
                voList.add(vo);
            });
            resultVo.setTsListVo(voList);
            resultVo.setTsValueListVo(valueList);
        } else if (type == 7) {
            List<CpVulnerabilityEntity> list = pseVulnerabilityService.getByProjectId(id);
            Map<String, List<CpVulnerabilityEntity>> collect = list.stream().collect(Collectors.groupingBy(CpVulnerabilityEntity::getEquipmentType));
            HashMap<String, Object> map = new HashMap<>();
            collect.forEach((k, v) -> {
                List<CpVulnerabilityEntity> collect1 = v.stream().sorted(Comparator.comparing(CpVulnerabilityEntity::getFloor).reversed()).collect(Collectors.toList());
                map.put(k, collect1);
            });
            resultVo.setMap(map);
        } else if (type == 9) {
            SmxDevicesEntity entity = ceVulnerabilityService.getByTableId(id);
            SmxDevicesVo vo = new SmxDevicesVo();
            BeanUtils.copyProperties(entity, vo);
            List<CztSmxDevicesValueEntity> list = ceVulnerabilityService.getValueByDevicesId(entity.getId());
            resultVo.setDevicesVo(vo);
            resultVo.setDevicesValueVoList(list);
        }
        return resultVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByIdAndType(UpdateParam param) {
        Integer type = param.getType();
        if (type == 1) {
            Integer upType = param.getUpType();
            if (upType == 1) {
                UpNetwork1Param network1Param = param.getNetwork1Param();
                upNetworkService.updateSimpleModelById(network1Param);
            } else if (upType == 2) {
                UpNetwork2Param network2Param = param.getNetwork2Param();
                upNetworkService.updateContinuousWeldingById(network2Param);
            } else if (upType == 3) {
                UpNetwork3Param network3Param = param.getNetwork3Param();
                upNetworkService.updateInterfaceTypeById(network3Param);
            }
        } else if (type == 2) {
            WaterSupplyParam waterSupplyParam = param.getWaterSupplyParam();
            wsfManagementService.updateWsfManagementById(waterSupplyParam);
        } else if (type == 3) {
            AirSupplyParam airSupplyParam = param.getAirSupplyParam();
            sgManagementService.updateAirSupplyById(airSupplyParam);
        } else if (type == 4) {
            BridgeParam bridgeParam = param.getBridgeParam();
            cbVulnerabilityService.updateBridgeById(bridgeParam,param.getBridgeType());
        } else if (type == 5) {
            RoadParam roadParam = param.getRoadParam();
            carVulnerabilityService.updateRoadById(roadParam);
        } else if (type == 6) {
            List<TsParam> tsParam = param.getTsParam();
            List<TsValueParam> valueParam = param.getValueParam();
            tsVulnerabilityService.updateById(tsParam);
            tsVulnerabilityService.delValueByTsId(tsParam.get(0).getTsId());
            tsVulnerabilityService.saveResult(valueParam,tsParam.get(0).getTsId());
        } else if (type == 7) {
            MainTableParam mainTableParam = param.getMainTableParam();
            List<CpVulnerabilityEntity> cpVulnerabilityList = param.getCpVulnerabilityList();
            pseVulnerabilityService.updateMainTable(mainTableParam);
            if(PlatformObjectUtils.isNotEmpty(cpVulnerabilityList)){
                cpVulnerabilityList.forEach(it->{
                    pseVulnerabilityService.updateValue(it);
                });
            }
        } else if (type == 9) {
            DevicesParam devicesParam = param.getDevicesParam();
            ceVulnerabilityService.updateDevicesById(devicesParam);
        }
    }

    @Override
    public RestResponse recalculate(Integer type, String id,Integer bridgeType) {
        RestResponse res = null;
        if (type == 1) {
            SmxUpNetworkEntity entity = upNetworkService.getByTableId(id);
            DataValidation1Dto dto = new DataValidation1Dto();
            BeanUtils.copyProperties(entity, dto);
            ArrayList<String> list = ValidationProcessor.validate(dto);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数【" + list + "】未填写完整,请补充完整再计算");
            }
            upNetworkService.countPseVulnerability(null, id);
            res = upNetworkService.countContinuousWelding(null, id);
            res = upNetworkService.countInterfaceWelding(null, id);
        } else if (type == 2) {
            SmxWaterSupplyEntity entity = wsfManagementService.getByTableId(id);
            ArrayList<String> list = ValidationProcessor.validate(entity);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数【" + list + "】未填写完整,请补充完整再计算");
            }
            res = wsfManagementService.calculationDamageDegree(null, id);
        } else if (type == 3) {
            SmxAirReceiverEntity entity = sgManagementService.getByTableId(id);
            ArrayList<String> list = ValidationProcessor.validate(entity);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数【" + list + "】未填写完整,请补充完整再计算");
            }
            sgManagementService.calculation(null, id);
            res = RestResponse.succeed("计算成功!");
        } else if (type == 4) {
            SmxBridgeEntity entity = cbVulnerabilityService.getByTableId(id,bridgeType);
            ArrayList<String> list = ValidationProcessor.validate(entity);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数【" + list + "】未填写完整,请补充完整再计算");
            }
            res = cbVulnerabilityService.cobVulnerability(null, id,bridgeType);
        } else if (type == 5) {
            SmxRoadEntity entity = carVulnerabilityService.getByTableId(id);
            ArrayList<String> list = ValidationProcessor.validate(entity);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数【" + list + "】未填写完整,请补充完整再计算");
            }
            res = carVulnerabilityService.crVulnerability(null, id);
        } else if (type == 6) {
            List<SmxTransformerSubstationEntity> dataList = tsVulnerabilityService.getByTableId(id);
            ArrayList<String> list = new ArrayList<>();
            dataList.forEach(it -> {
                list.addAll(ValidationProcessor.validate(it));
            });
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数未填写完整,请补充完整再计算");
            }
            res = tsVulnerabilityService.caTsVulnerability(null, id);
        } else if (type == 9) {
            SmxDevicesEntity entity = ceVulnerabilityService.getByTableId(id);
            ArrayList<String> list = ValidationProcessor.validate(entity);
            if (PlatformObjectUtils.isNotEmpty(list)) {
                return RestResponse.fail("计算参数【" + list + "】未填写完整,请补充完整再计算");
            }
            res = ceVulnerabilityService.caCeVulnerability(null, id);
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByTypeAndId(List<DeleteParam> params) {
        params.forEach(it->{
            SmxMainTableEntity entity = valEngineeringRepository.getById(it.getId());
            lifelineEngineeringRepository.deleteMainByTableId(it.getId());
            valEngineeringRepository.deleteByTypeAndTableId(it.getType(), it.getId(),it.getBridgeType());
            int count = lifelineEngineeringRepository.getDataCountByVersionId(it.getType(),entity.getVersionId());
            if (it.getType() == 4) {
                count += lifelineEngineeringRepository.getBridgeLineCountByVersionId(entity.getVersionId());
            }
            if(count == 0){
                lifelineEngineeringRepository.deleteByTypeAndVersionId(entity.getVersionId());
            }
        });
    }
}
